package com.cloud.grainmall.web;


import com.alibaba.fastjson.JSON;
import com.cloud.common.utils.HttpUtils;
import com.cloud.grainmall.vo.SocialUser;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;

/**
 * @author lisw
 * @create 2021/7/25 16:04
 */
@Controller
@RequestMapping("/oauth2.0")
public class OAuth2Controller {

    @GetMapping("/weibo/success")
    public String weiboOAuth2(@RequestParam("code")String code) throws Exception {
        HashMap<String, String> map = new HashMap<>();
        map.put("clientId", "4102776118");
        map.put("client_secret", "da04cd5b52df60e6b1bf3f7bb0c1abbf");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.grainmall.com:81/oauth2.0/weibo/success");
        map.put("code", code);
        //1、根据code码获取token
        /**
         * https://api.weibo.com/oauth2/access_token
         * ?client_id=4102776118
         * &client_secret=da04cd5b52df60e6b1bf3f7bb0c1abbf
         * &grant_type=authorization_code
         * &redirect_uri=http://auth.grainmall.com:81/oauth2.0/weibo/success
         * &code=48dfd868dd1a169c921c2b087929afae
         */
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post",
                null, null,map);

        //2、处理。如果获取成功，那就说明用户登录成功，登录成功就跳转首页
        if (response.getStatusLine().getStatusCode() == 200){
            //TODO 微博服务并未及时更新，稍后处理 2021-7-25 223
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //1）、当前用户如果是第一次登录网站，（为当前社交用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）

        }else {
            return "redirect:http://auth.grainmall.com:81/login";
        }
        return "";
    }
}
